import { AxiosRequestConfig } from '@ohos/axios';
import { Interceptor } from './Interceptor';
import { RealInterceptorChain } from './RealInterceptorChain';
import { Response } from './Response';
import { Utils } from './Utils';

export class CallServerInterceptor implements Interceptor {
  async intercept(chain: Interceptor.Chain): Promise<Response> {
    const realChain = chain as RealInterceptorChain
    const request = realChain.request
    const requestBody = request.body

    const url = Utils.isEmpty(request.url) ? undefined : request.url
    const baseUrl = Utils.isEmpty(request.baseUrl) ? undefined : request.baseUrl
    const config = {
      url: url,
      baseURL: baseUrl,
      method: request.httpMethod.method,
      headers: Object.fromEntries(request.headers),
      params: Object.fromEntries(request.queryParams),
      data: request.body
    } as AxiosRequestConfig
    const axiosResponse = await realChain.call.httpDecorator.axios.request(config)
    const responseBuilder = new Response.Builder()
      .request(request)
      .message(axiosResponse.statusText)
      .code(axiosResponse.status)
      .body(axiosResponse.data)

    Object.entries(axiosResponse.headers).forEach(([k, v]) => {
      responseBuilder.header(k, v)
    })


    return Promise.resolve(responseBuilder.build())
  }
}